﻿using Models.WebClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using UtilsCache;
using ServiceWeb.DBGateway;
namespace ServiceWeb.WebClient
{
    public class SerivceDeviceValueCurrent
    {

        public List<ViewDeviceCurrentValue> getViewDeviceCurrentValue(string pguid, string dguid, string modelno)
        {
            List<ViewDeviceCurrentValue> viewDeviceCurrentValues = new List<ViewDeviceCurrentValue>();
            ViewDeviceCurrentValue viewDeviceCurrentValue = new ViewDeviceCurrentValue();

            string getDeviceGuidsObject = UtilMemoryCacheHelper.get<string>("getValueCurrentByProduct_" + pguid + dguid + modelno);
            List<string> devices = new List<string>();
            if (string.IsNullOrEmpty(getDeviceGuidsObject))
            {

                DataTable dt = new DBIotDeviceValueCurrent().getValueCurrentByProduct(pguid, dguid, modelno);
                foreach (DataRow dr in dt.Rows)
                {
                    viewDeviceCurrentValue = new ViewDeviceCurrentValue();
                    viewDeviceCurrentValue.modelNo = int.Parse(dr["d_p_model_no"].ToString());
                    viewDeviceCurrentValue.key = dr["vc_key"].ToString();
                    viewDeviceCurrentValue.value = dr["vc_value"].ToString();
                    viewDeviceCurrentValue.addtime =DateTime.Parse( dr["vc_add_time"].ToString());
                    viewDeviceCurrentValues.Add(viewDeviceCurrentValue);

                    devices.Add((dr["d_guid"].ToString() + dr["vc_key"].ToString()).ToLower());

                    string data = JsonConvert.SerializeObject(viewDeviceCurrentValue);
                    UtilMemoryCacheHelper.set<string>("deviceValue_" + (dr["d_guid"].ToString() + dr["vc_key"].ToString()).ToLower(), data, 60);
                }
                string dataDevices = JsonConvert.SerializeObject(devices);
                UtilMemoryCacheHelper.set<string>("getValueCurrentByProduct_" + pguid + dguid + modelno, dataDevices, 30);
            }
            else
            {
                devices = JsonConvert.DeserializeObject<List<string>>(getDeviceGuidsObject);
                foreach (string deviceGuidkey in devices.Distinct().ToList())
                {
                    string data = UtilMemoryCacheHelper.get<string>("deviceValue_" + deviceGuidkey.ToLower());
                    //Console.WriteLine(deviceGuid + "--------------" + data);
                    if (!string.IsNullOrEmpty(data))
                    {
                        viewDeviceCurrentValue = new ViewDeviceCurrentValue();
                        viewDeviceCurrentValue = JsonConvert.DeserializeObject<ViewDeviceCurrentValue>(data);
                        viewDeviceCurrentValues.Add(viewDeviceCurrentValue);
                    }
                }
            }
            return viewDeviceCurrentValues;
        }

       
    }
}